package com.crimerank;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crimerank.data.StopCrime;
import com.crimerank.data.Train;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class StationPrediction extends BaseActivity {

	StopCrime obj = null;
	Bundle loc;
	double lat, lon;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stationprediction);

		// Get lat/long from the Intent extras
		this.loc = getIntent().getExtras().getBundle("loc");
		lat = loc.getDouble("lat");
		lon = loc.getDouble("lon");
		
		obj = (StopCrime)getIntent().getSerializableExtra("StopCrimeObj");
		
		// Request data from server 
		requestData(obj.getStop_id());
		
		// Set station name and crime rank
		TextView stationName = (TextView) findViewById(R.id.stationPredictionName);
		stationName.setText(obj.getName());
		
		TextView stationRank = (TextView) findViewById(R.id.stationPredictionRank);
		stationRank.setText("Rank: " + obj.getRank());

	}

	private void requestData(String stationCode) {
		try {
			String url = getResources().getString(
					R.string.URL_STATION_PREDICTION);
			String query = String.format("api_key=%s",
					URLEncoder.encode("s2f5rag8pa5fz53mg2e7s4et", "UTF-8"));

			// Perform the HTTP request
			String result = doHttpRequest(url + stationCode, query);

			// Process result and update display
			ArrayList<Train> list = processJson(result);

			// Add the results to table view
			displayList(list);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Train> processJson(String str) throws JSONException {
		ArrayList<Train> list = new ArrayList<Train>();

		// Loop thru JSON array and parse out train info
		JSONObject jo = new JSONObject(str);
		JSONArray ja = jo.getJSONArray("Trains");
		for (int i = 0; i < ja.length(); i++) {
			Train train = new Train();
			JSONObject tmp = (JSONObject) ja.get(i);
			train.setCars(tmp.getString("Car"));
			train.setDestination(tmp.getString("Destination"));
			train.setDestinationCode(tmp.getString("DestinationCode"));
			train.setDestinationName(tmp.getString("DestinationName"));
			train.setGroup(tmp.getInt("Group"));
			train.setLine(tmp.getString("Line"));
			train.setLocationCode(tmp.getString("LocationCode"));
			train.setLocationName(tmp.getString("LocationName"));
			train.setMin(tmp.getString("Min"));
			list.add(train);
		}

		return list;
	}

	private void displayList(ArrayList<Train> list) {

		// Find Tablelayout defined in main.xml
		TableLayout tl = (TableLayout) findViewById(R.id.predictionTable);
		tl.removeAllViews();

		TableRow tr = new TableRow(this);

		TextView text = new TextView(this);
		text.setText("Line");
		text.setSingleLine(true);
		tr.addView(text);

		text = new TextView(this);
		text.setText("Cars");
		text.setSingleLine(true);
		tr.addView(text);

		text = new TextView(this);
		text.setText("Dest");
		text.setSingleLine(true);
		tr.addView(text);

		text = new TextView(this);
		text.setText("Min");
		text.setSingleLine(true);
		tr.addView(text);

		tl.addView(tr);

		for (Train train : list) {
			addRow(tl, train);
		}

		TextView lastUpdate = (TextView) findViewById(R.id.lastUpdate);
		Time time = new Time();
		time.setToNow();
		lastUpdate.setText("Last Updated: " + time.format("%Y/%m/%d %H:%M:%S"));
	}

	public void addRow(TableLayout tl, Train train) {
		// Create a new row to be added
		TableRow tr = new TableRow(this);

		// Add row-content
		ImageView image = new ImageView(this);
		String lineColor = train.getLine();
		image.setImageResource(getlineColorIcon(lineColor));
		tr.addView(image);

		TextView text = new TextView(this);
		text.setText(train.getCars());
		text.setSingleLine(true);
		tr.addView(text);

		text = new TextView(this);
		text.setText(train.getDestination());
		text.setSingleLine(true);
		tr.addView(text);

		text = new TextView(this);
		text.setText(train.getMin());
		text.setSingleLine(true);
		tr.addView(text);

		tl.addView(tr);
	}

	private int getlineColorIcon(String color) {
		if (color.equals("BL")) {
			return R.drawable.blue_b;
		} else if (color.equals("OR")) {
			return R.drawable.orange_b;
		} else if (color.equals("RD")) {
			return R.drawable.red_b;
		} else if (color.equals("YL")) {
			return R.drawable.yellow_b;
		} else if (color.equals("GR")) {
			return R.drawable.green_b;
		}

		return R.drawable.null_b;
	}

	public void onClick(View v) {
		Intent myIntent;
		switch (v.getId()) {
		case (R.id.imageMap):
			myIntent = new Intent(v.getContext(), Map.class);
			myIntent.putExtra("points", getIntent()
					.getParcelableArrayListExtra("points"));
			myIntent.putExtra("mapType", "geoPoint");
			myIntent.putExtra("loc", loc);
			startActivityForResult(myIntent, 0);

			// This will open up Google Maps outside the app with directions.
			// String start = getIntent().getStringExtra("start");
			// String finish = getIntent().getStringExtra("finish");
			// Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
			// Uri.parse("http://maps.google.com/maps?saddr=" + start +
			// "&daddr=" + finish));
			// startActivity(intent);
			break;
		case (R.id.imageCrime):
			myIntent = new Intent(v.getContext(), StationCrime.class);
			myIntent.putExtra("StopCrimeObj", obj);
			startActivityForResult(myIntent, 0);
			break;
		case (R.id.imageHome):
			myIntent = new Intent(v.getContext(), Home.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(myIntent, 0);
			break;
		case (R.id.imageRefresh):
			requestData(obj.getStop_id());
			break;
		}
	}
}
